import request from '@/utils/request'
import axios from 'axios'
import store from '@/store'
const CancelToken = axios.CancelToken
export let cancel
// const source = new CancelToken(function executor (c) {
//   cancel = c
// })

/**
 * 文件下载
 * @param {string} fileType 文件类型
 * @param {string} fileID 文件编号
 * @param {string} other 其它信息，若是会议文件则填写会议编号，默认填0
 */
export const fileDownload = (fileType, fileID, other, startBytes, endBytes) => {
  return request.get(`file/download/${fileType}/${fileID}/${other || 0}?${startBytes}`, {
    headers: {
      Range: `bytes=${startBytes}-${endBytes}`
    }
  })
}

/**
 * 文件上传
 * @param {formData} file 文件
 */
export const fileUpload = (file) => {
  return request.post('file/upload',
    file, {
      onUploadProgress: (e) => {
        if (!store.state.dialogData) {
          store.commit('filePage/set_dialogData', {
            mainTips: [
              '正在上传...'
            ],
            subTips: '请耐心等待...',
            btnList: [
              {
                name: '取消',
                color: 'white',
                type: 'cancel'
              }
            ],
            ifShowPercents: true
          })
        }
        if (e.lengthComputable) {
          store.commit('file/set_uploadPercent', (e.loaded / e.total * 100).toFixed(0))
          if (e.loaded === e.total) {
            store.commit('filePage/set_dialogData', {
              mainTips: [
                '上传成功，正在处理中'
              ],
              ifShowPercents: true
            })
          }
        }
      },
      cancelToken: new CancelToken(function executor (c) {
        cancel = c
      })
    }
  ).catch(err => err)
}
